import asyncio
import datetime
import os
import random
import textwrap
import threading

import aiofiles
import aiofiles.os
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import (
    KeyboardButton,
    ReplyKeyboardMarkup,
)

import client
import client_kb
import sqlite_db
from common_utils import compare_date, paste_watermark
from create_bot import bot
from .br_country_dir.br_utils import is_portuguese, pt_transliterate


class FSM(StatesGroup):
    create_br_pass = State()
    create_br_pass_family = State()
    create_br_pass_name = State()
    create_br_pass_date_birth = State()
    create_br_pass_number = State()
    create_br_pass_natcion = State()
    create_br_pass_place_birth = State()
    create_br_pass_gender = State()
    create_br_pass_date_doc = State()
    create_br_pass_photo = State()
    create_br_pass_signature = State()
    create_br_pass_holo = State()
    create_br_pass_size = State()

    change_br_pass = State()
    change_br_pass_what = State()
    change_br_pass_family = State()
    change_br_pass_name = State()
    change_br_pass_date_birth = State()
    change_br_pass_number = State()
    change_br_pass_natcion = State()
    change_br_pass_place_birth = State()
    change_br_pass_gender = State()
    change_br_pass_date_doc = State()
    change_br_pass_photo = State()
    change_br_pass_signature = State()
    change_br_pass_holo = State()
    change_br_pass_go = State()

    create_br_bill_family = State()
    create_br_bill_name = State()
    create_br_bill_flate_number = State()
    create_br_bill_street = State()
    create_br_bill_city = State()
    create_br_bill_postcode = State()

    change_br_bill = State()
    change_br_bill_what = State()
    change_br_bill_go = State()

    ###################
    create_br_id_name = State()
    create_br_id_family = State()
    create_br_id_name_father = State()
    create_br_id_name_mother = State()
    create_br_id_date_birth = State()
    create_br_id_place_birth = State()
    create_br_id_pass_number = State()
    create_br_id_pass_number_cpf = State()
    create_br_id_date_doc = State()
    create_br_id_place_doc = State()
    create_br_id_photo = State()
    create_br_id_signature = State()
    create_br_id_size = State()

    change_br_id = State()
    change_br_id_what = State()

    change_br_id_go = State()


async def command_create_br(message: types.Message):
    user_id = message.from_user.id
    await sqlite_db.sql_check_user(user_id)
    await bot.send_message(
        user_id, "Выберите документ для создания", reply_markup=client_kb.kb_br
    )
    await FSM.create_br_pass.set()


###################brbill
async def command_create_br_bill(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    country = "br_bill"
    await sqlite_db.sql_add_country_user(user_id, country)
    async with aiofiles.open(f"./files/example/bill_br.jpg", "rb") as file:
        await bot.send_photo(user_id, photo=file)
    messagetoedit = await bot.send_message(
        user_id,
        f"Данные клиента\n"
        f"Фамилия:\n"
        f"Имя:\n"
        f"Номер дома:\n"
        f"Улица:\n"
        f"Город:\n"
        f"Посткод:",
        reply_markup=client_kb.cancelledKeyboard,
    )
    msg_delete = await bot.send_message(user_id, "Введите фамилию ✏️")
    async with state.proxy() as data:
        data["message_edit"] = messagetoedit["message_id"]
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.create_br_bill_family.set()


async def command_create_br_bill_family(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["family"] = message.text
    if message.text == "Назад ◀️":
        user_id = message.from_user.id
        await sqlite_db.sql_check_user(user_id)
        await bot.send_message(
            user_id, "Выберите документ для создания", reply_markup=client_kb.kb_br
        )
        await FSM.create_br_pass.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f"Имя:\n"
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
        )
        msg_delete = await bot.send_message(
            user_id, "Введите имя ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_name.set()


async def command_create_br_bill_name(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["name"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f"Фамилия:\n"
            f"Имя:\n"
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(user_id, "Введите фамилию ✏️")
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_family.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер дома ✏️\n" 'либо нажмите "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_flate_number.set()


async def command_create_br_bill_flate_number(
    message: types.Message, state: FSMContext
):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["flate_number"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f"Имя:\n"
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
        )
        msg_delete = await bot.send_message(
            user_id, "Введите имя ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_name.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название улицы ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_street.set()


async def command_create_br_bill_street(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["street"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер дома ✏️\n" 'либо нажмите "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_flate_number.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название города ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_city.set()


async def command_create_br_bill_city(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["city"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название улицы ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_street.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f'✅ Город: {data["city"]}\n'
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id, "Введите посткод ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_postcode.set()


async def command_create_br_bill_postcode(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["postcode"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название города ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_bill_city.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f'✅ Город: {data["city"]}\n'
            f'✅ Посткод: {data["postcode"]}',
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Ожидайте генерируется...",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
            try:
                thr = threading.Thread(
                    target=process_generate_bill,
                    args=(user_id, data),
                    name=f"thr-{user_id}",
                )
                thr.start()
                while thr.is_alive():
                    await asyncio.sleep(1)
                async with aiofiles.open(
                    f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                    "rb",
                ) as f:
                    await bot.send_document(chat_id=user_id, document=f)
                await bot.send_message(
                    user_id,
                    "Завершите покупку документа.",
                    reply_markup=client_kb.kb_br_finish_bill,
                )
                try:
                    await bot.delete_message(
                        chat_id=user_id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                await FSM.change_br_bill.set()
            except Exception as ex:
                print("Ошибка в генерации br bill:", ex)
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "Ошибка при генерации, проверьте введенные данные",
                        reply_markup=client_kb.kb_br_change_error,
                    )
                    data["message_edit"] = messagetoedit["message_id"]
                    data["msg_delete"] = msg_delete["message_id"]
                    await FSM.change_br_bill.set()


async def command_change_br_bill(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    try:
        await bot.delete_message(
            chat_id=callback.from_user.id, message_id=callback.message.message_id
        )
    except:
        pass
    msg_delete = await bot.send_message(
        user_id,
        "Выберите параметр, который хотите изменить",
        reply_markup=client_kb.kb_br_change_go_bill,
    )
    async with state.proxy() as data:
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_what.set()


async def command_change_br_bill_family(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите фамилию ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "family"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_go.set()


async def command_change_br_bill_name(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите имя ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "name"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_go.set()


async def command_change_br_bill_flate_number(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Введите номер дома ✏️\n" 'либо нажмите "Пропустить"',
        reply_markup=client_kb.kb_skip,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "flate_number"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_go.set()


async def command_change_br_bill_street(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите название улицы ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "street"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_go.set()


async def command_change_br_bill_city(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите название города ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "city"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_go.set()


async def command_change_br_bill_postcode(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите посткод ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "postcode"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_bill_go.set()


async def command_change_br_bill_go(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    try:
        await bot.delete_message(
            chat_id=message.from_user.id, message_id=message.message_id
        )
    except:
        pass
    async with state.proxy() as data:
        if data["what_change"] == "family":
            async with state.proxy() as data:
                data["family"] = msg
                data["sign"] = data["family"].capitalize()
                if is_portuguese(data["sign"]):
                    data["sign"] = pt_transliterate(data["sign"])
                if len(data["sign"]) > 5:
                    data["sign"] = data["sign"][: random.randint(3, 5)]
                await state.update_data(sign=data["sign"])
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации br bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_bill.set()
        elif data["what_change"] == "name":
            async with state.proxy() as data:
                data["name"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации br bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_bill.set()
        elif data["what_change"] == "flate_number":
            async with state.proxy() as data:
                data["flate_number"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации br bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_bill.set()
        elif data["what_change"] == "street":
            async with state.proxy() as data:
                data["street"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации br bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_bill.set()
        elif data["what_change"] == "city":
            async with state.proxy() as data:
                data["city"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации br bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_bill.set()
        elif data["what_change"] == "postcode":
            async with state.proxy() as data:
                data["postcode"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации br bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_bill.set()


async def command_pay_br_bill(callback: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data["pay_country"] = "br_bill"
    await client.command_promo_quest(callback, state)


def process_generate_bill(user_id, data):
    try:
        bill = Image.open(f"./files/br_pass/br_bill/bill.png").convert("RGBA")
        txt = Image.new("RGBA", bill.size, (255, 255, 255, 0))
        fnt_semibold = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_SemiBold.ttf", size=39
        )
        fnt_semibold_one = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_SemiBold.ttf", size=40
        )
        fnt_semibold_two = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_SemiBold.ttf", size=34
        )
        fnt_semibold_three = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_SemiBold.ttf", size=30
        )
        fnt_bold = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_Bold.ttf", size=30
        )
        fnt_bold_one = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_Bold.ttf", size=38
        )
        fnt_regular = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_Regular.ttf", size=40
        )
        fnt_regular_one = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_Regular.ttf", size=34
        )
        fnt_regular_two = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_Regular.ttf", size=30
        )
        fnt_semibold_italic = ImageFont.truetype(
            f"./files/br_pass/br_bill/fonts/OpenSans_SemiBoldItalic.ttf", size=34
        )

        go_txt = ImageDraw.Draw(txt)

        # go_txt.text(xy=(1094, 89), text=f"{str(data['name'])} CITIZEN", font=fnt_bold_one,fill=(57, 66, 133, 255))

        if len(str(data["name"])) <= 8:
            go_txt.text(
                xy=(1094, 89),
                text=f"{str(data['name'])} CITIZEN".upper(),
                font=fnt_bold_one,
                fill=(57, 66, 133, 255),
            )
            go_txt.text(
                xy=(850, 150),
                text=f"Independence Street, 1968",
                font=fnt_regular_one,
                fill="#000000",
            )
            go_txt.text(
                xy=(850, 190),
                text=f"Reborn, Macapa - AP",
                font=fnt_regular_one,
                fill="#000000",
            )
            go_txt.text(
                xy=(850, 230), text=f"68907-203", font=fnt_regular_one, fill="#000000"
            )
            go_txt.text(
                xy=(850, 270), text=f"Brazil", font=fnt_regular_one, fill="#000000"
            )

        else:
            nameWrap = textwrap.wrap(str(data["name"]), width=8)
            print(nameWrap)
            go_txt.text(
                xy=(1094, 89),
                text=f"{nameWrap[0]}".upper(),
                font=fnt_bold_one,
                fill=(57, 66, 133, 255),
            )
            go_txt.text(
                xy=(850, 130),
                text=f"{nameWrap[1]} CITIZEN".upper(),
                font=fnt_bold_one,
                fill=(57, 66, 133, 255),
            )

            go_txt.text(
                xy=(850, 190),
                text=f"Independence Street, 1968",
                font=fnt_regular_one,
                fill="#000000",
            )
            go_txt.text(
                xy=(850, 230),
                text=f"Reborn, Macapa - AP",
                font=fnt_regular_one,
                fill="#000000",
            )
            go_txt.text(
                xy=(850, 270), text=f"68907-203", font=fnt_regular_one, fill="#000000"
            )
            go_txt.text(
                xy=(850, 310), text=f"Brazil", font=fnt_regular_one, fill="#000000"
            )

        acc_number = str(random.randint(100000000, 999999999))
        go_txt.text(
            xy=(1998, 133), text=f"9{acc_number}", font=fnt_regular_one, fill="#000000"
        )
        go_txt.text(
            xy=(2123, 2363), text=f"9{acc_number}", font=fnt_regular_two, fill="#000000"
        )

        service_number = str(random.randint(100000000, 999999999))
        go_txt.text(
            xy=(1988, 1229),
            text=f"2{service_number}",
            font=fnt_regular_two,
            fill="#000000",
        )

        meter = str(random.randint(100000, 999999))
        go_txt.text(
            xy=(167, 987), text=f"0{meter}", font=fnt_regular_two, fill="#000000"
        )

        fio = str(data["name"]) + " " + str(data["family"])
        go_txt.text(
            xy=(161, 2709), text=f"{fio.upper()}", font=fnt_semibold_one, fill="#000000"
        )

        if data["flate_number"] == "Пропустить":
            street = str(data["street"].title())
            go_txt.text(
                xy=(162, 2766),
                text=f"{street} , {str(data['city'].upper())},",
                font=fnt_regular,
                fill="#000000",
            )
        else:
            street = str(data["street"].capitalize()) + " " + str(data["flate_number"])
            go_txt.text(
                xy=(162, 2766),
                text=f"{street} , {str(data['city'].upper())},",
                font=fnt_regular,
                fill="#000000",
            )
        go_txt.text(
            xy=(158, 2823),
            text=f"{data['postcode'].upper()}, BRAZIL",
            font=fnt_regular,
            fill="#000000",
        )

        amount = random.uniform(26.66, 30.70)
        amounts = round(amount, 2)
        amounts = "{:.2f}".format(amounts)
        print(amounts)

        go_txt.text(
            xy=(2183, 2470), text=f"R${amounts}", font=fnt_semibold_two, fill="#ffffff"
        )
        ########
        go_txt.text(
            xy=(1246, 561), text=f"R${amounts}", font=fnt_semibold_two, fill="#000000"
        )
        ########
        go_txt.text(
            xy=(1247, 612), text=f"R${amounts}", font=fnt_regular_one, fill="#000000"
        )

        go_txt.text(
            xy=(1229, 658), text=f"R${amounts}", font=fnt_semibold, fill="#ffffff"
        )

        billing_amount = float(amounts) / 2
        billing_amount = round(billing_amount, 2)
        billing_amount = "{:.2f}".format(billing_amount)
        go_txt.text(
            xy=(1247, 457),
            text=f"R${billing_amount}",
            font=fnt_regular_one,
            fill="#000000",
        )
        go_txt.text(
            xy=(1236, 509),
            text=f"-R${billing_amount}",
            font=fnt_regular_one,
            fill="#000000",
        )

        gas_charge_generate = random.uniform(0.120000, 0.560000)
        gas_charge_generate = round(gas_charge_generate, 6)
        gas_charge_rand_go = "{:.6f}".format(gas_charge_generate)
        go_txt.text(
            xy=(713, 1518),
            text=f"${gas_charge_rand_go}",
            font=fnt_regular_two,
            fill="#000000",
        )
        gas_charge_amount = 15.53 * float(gas_charge_generate)
        gas_charge_amount = round(gas_charge_amount, 2)
        gas_charge_amount = "{:.2f}".format(gas_charge_amount)
        print(gas_charge_amount)
        go_txt.text(
            xy=(1429, 1518),
            text=f"R${gas_charge_amount}",
            font=fnt_regular_two,
            fill="#000000",
        )
        go_txt.text(
            xy=(1427, 1576),
            text=f"R${gas_charge_amount}",
            font=fnt_bold,
            fill="#000000",
        )

        total_usage_amount = float(amounts) - float(gas_charge_amount)
        total_usage_amount = round(total_usage_amount, 2)
        total_usage_amount = "{:.2f}".format(total_usage_amount)
        go_txt.text(
            xy=(1411, 1353),
            text=f"R${total_usage_amount}",
            font=fnt_bold,
            fill="#000000",
        )

        delivery_charge_amount = random.uniform(0.600000, 0.940000)
        delivery_charge_amount = round(delivery_charge_amount, 6)
        delivery_charge_rand_go = "{:.6f}".format(delivery_charge_amount)
        go_txt.text(
            xy=(713, 1292),
            text=f"${delivery_charge_rand_go}",
            font=fnt_regular_two,
            fill="#000000",
        )
        delivery_charge_amount = 15.53 * float(delivery_charge_rand_go)
        delivery_charge_amount = round(delivery_charge_amount, 2)
        delivery_charge_amount = "{:.2f}".format(delivery_charge_amount)
        go_txt.text(
            xy=(1412, 1292),
            text=f"R${delivery_charge_amount}",
            font=fnt_regular_two,
            fill="#000000",
        )

        customer_amount = (float(amounts) - float(delivery_charge_amount)) - float(
            gas_charge_amount
        )
        customer_amount = round(customer_amount, 2)
        customer_amount = "{:.2f}".format(customer_amount)
        go_txt.text(
            xy=(1412, 1229),
            text=f"R${customer_amount}",
            font=fnt_regular_two,
            fill="#000000",
        )

        dict_month = {
            "01": "January",
            "02": "February",
            "03": "March",
            "04": "April",
            "05": "May",
            "06": "June",
            "07": "July",
            "08": "August",
            "09": "September",
            "10": "October",
            "11": "November",
            "12": "December",
        }

        today = datetime.date.today()
        prev_month = today.month - 1 if today.month > 1 else 12
        prev_year = today.year if prev_month != 12 else today.year - 1
        random_day = random.randint(2, 6)
        prev_date = datetime.date(prev_year, prev_month, day=1)
        go_txt.text(
            xy=(1493, 88),
            text=f"{dict_month[str(prev_date.strftime('%m'))]} {random_day},"
            f" {prev_date.strftime('%Y')}",
            font=fnt_regular_one,
            fill="#000000",
        )
        next_rand_day = int(random_day) - 1
        go_txt.text(
            xy=(2102, 446),
            text=f"{dict_month[str(today.strftime('%m'))]} {next_rand_day},",
            font=fnt_semibold_italic,
            fill="#000000",
        )
        go_txt.text(
            xy=(1548, 491),
            text=f"{today.strftime('%Y')}",
            font=fnt_semibold_italic,
            fill="#000000",
        )

        prewtwo_month = prev_date.month - 1 if prev_date.month > 1 else 12
        prewtwo_year = prev_date.year if prewtwo_month != 12 else prev_date.year - 1
        prewtwo_date = datetime.date(prewtwo_year, prewtwo_month, day=1)
        prewtwo_random_day = random.randint(4, 8)
        print(prewtwo_date)
        go_txt.text(
            xy=(610, 389),
            text=f"{dict_month[str(prewtwo_date.strftime('%m'))]} {prewtwo_random_day},"
            f" {prewtwo_date.strftime('%Y')}",
            font=fnt_bold_one,
            fill=(249, 50, 45, 255),
        )
        prewtwo_random_day_new = int(prewtwo_random_day) + 10
        go_txt.text(
            xy=(501, 509),
            text=f"{dict_month[str(prewtwo_date.strftime('%m'))]} {prewtwo_random_day_new},"
            f" {prewtwo_date.strftime('%Y')}",
            font=fnt_regular_one,
            fill="#000000",
        )

        random_day_three = random.randint(25, 28)
        go_txt.text(
            xy=(453, 658),
            text=f"{dict_month[str(prev_date.strftime('%m'))]} {random_day_three},"
            f" {prev_date.strftime('%Y')}",
            font=fnt_semibold,
            fill="#ffffff",
        )
        go_txt.text(
            xy=(2015, 2526),
            text=f"{dict_month[str(prev_date.strftime('%m'))]} {random_day_three},"
            f" {prev_date.strftime('%Y')}",
            font=fnt_semibold_three,
            fill="#000000",
        )

        go_txt.text(
            xy=(334, 987),
            text=f"{str(prewtwo_date.strftime('%m'))}-0{prewtwo_random_day}-"
            f"{prewtwo_date.strftime('%y')}",
            font=fnt_regular_two,
            fill="#000000",
        )
        go_txt.text(
            xy=(502, 987),
            text=f"{str(prev_date.strftime('%m'))}-0{int(prewtwo_random_day) + 1}-"
            f"{prev_date.strftime('%y')}",
            font=fnt_regular_two,
            fill="#000000",
        )

        prev_year_two = prev_date.year - 1
        prev_year_two_date = datetime.date(prev_year_two, prev_month, day=1)
        go_txt.text(
            xy=(160, 1824),
            text=f"{dict_month[str(prev_date.strftime('%m'))]} "
            f"{prev_year_two_date.strftime('%Y')}",
            font=fnt_regular_two,
            fill="#000000",
        )
        go_txt.text(
            xy=(160, 1890),
            text=f"{dict_month[str(prev_date.strftime('%m'))]} "
            f"{prev_date.strftime('%Y')}",
            font=fnt_regular_two,
            fill="#000000",
        )

        result = Image.alpha_composite(bill, txt)
        result.save(f"./files/br_pass/br_bill/photo_usr/{user_id}_completed.png")

        image_path = f"./files/br_pass/br_bill/photo_usr/{user_id}_completed.png"
        path_to_save = f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png"
        paste_watermark(image_path, path_to_save)
        print("gotovo")
    except Exception as ex:
        print("ошибка process_br_bill: ", ex)
        try:
            os.remove(f"./files/br_pass/br_bill/photo_usr/{user_id}.png")
        except:
            pass
        try:
            os.remove(f"./files/br_pass/br_bill/photo_usr/{user_id}_completed.png")
        except:
            pass
        try:
            os.remove(f"./files/br_pass/br_bill/photo_usr/{user_id}_completed_wm.png")
        except:
            pass
        return


###################brid
async def command_create_br_id(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    country = "br_id"
    await sqlite_db.sql_add_country_user(user_id, country)
    async with aiofiles.open(f"./files/example/id_br.jpg", "rb") as file:
        await bot.send_photo(user_id, photo=file)
    messagetoedit = await bot.send_message(
        user_id,
        f"Данные клиента\n"
        f"Имя:\n"
        f"Фамилия:\n"
        f"ФИО отца:\n"
        f"ФИО матери:\n"
        f"Дата рождения:\n"
        f"Место рождения:\n"
        f"Номер паспорта (RG):\n"
        f"Номер паспорта (CPF):\n"
        f"Дата выдачи:\n"
        f"Место выдачи:\n"
        f"Фотография:\n"
        f"Подпись:\n"
        f"Размер документа:",
        reply_markup=client_kb.cancelledKeyboard,
    )
    msg_delete = await bot.send_message(user_id, "Введите имя ✏️")
    async with state.proxy() as data:
        data["message_edit"] = messagetoedit["message_id"]
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.create_br_id_name.set()


async def command_create_br_id_name(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["name"] = message.text
    if message.text == "Назад ◀️":
        user_id = message.from_user.id
        await sqlite_db.sql_check_user(user_id)
        await bot.send_message(
            user_id, "Выберите документ для создания", reply_markup=client_kb.kb_br
        )
        await FSM.create_br_pass.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f"Фамилия:\n"
            f"ФИО отца:\n"
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id, "Введите фамилию ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_family.set()


async def command_create_br_id_family(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["family"] = message.text
        data["sign"] = data["family"].capitalize()
        if is_portuguese(data["sign"]):
            data["sign"] = pt_transliterate(data["sign"])
        if len(data["sign"]) > 5:
            data["sign"] = data["sign"][: random.randint(3, 5)]
        await state.update_data(sign=data["sign"])
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f"Имя:\n"
            f"Фамилия:\n"
            f"ФИО отца:\n"
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(user_id, "Введите имя ✏️")
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_name.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f"ФИО отца:\n"
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Назад ◀️"), types.KeyboardButton("Пропустить"))
        msg_delete = await bot.send_message(
            user_id, "Введите ФИО отца ✏️", reply_markup=kb
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_name_father.set()


async def command_create_br_id_name_father(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["name_father"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f"Фамилия:\n"
            f"ФИО отца:\n"
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Назад ◀️"), types.KeyboardButton("Пропустить"))
        msg_delete = await bot.send_message(
            user_id, "Введите фамилию ✏️", reply_markup=kb
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_family.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id, "Введите ФИО матери ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_name_mother.set()


async def command_create_br_id_name_mother(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["name_mother"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f"ФИО отца:\n"
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Назад ◀️"), types.KeyboardButton("Пропустить"))
        msg_delete = await bot.send_message(
            user_id, "Введите ФИО отца ✏️", reply_markup=kb
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_name_father.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите дату рождения ✏️\n" "Формат дд.мм.гггг",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_date_birth.set()


async def command_create_br_id_date_birth(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["date_birth"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f"ФИО матери:\n"
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(user_id, "Введите ФИО матери ✏️")
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_name_mother.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        if (
            len(msg) == 10
            and msg[2] == "."
            and msg[5] == "."
            and msg[:2].isdigit()
            and msg[3:5].isdigit()
            and msg[6:].isdigit()
        ):
            if int(msg[:2]) <= 31 and int(msg[3:5]) <= 12:
                async with state.proxy() as data:
                    data["date_birth"] = message.text
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["message_edit"]
                    )
                except:
                    pass
                messagetoedit = await bot.send_message(
                    user_id,
                    f"Данные клиента\n"
                    f'✅ Имя: {data["name"]}\n'
                    f'✅ Фамилия: {data["family"]}\n'
                    f'✅ ФИО отца: {data["name_father"]}\n'
                    f'✅ ФИО матери: {data["name_mother"]}\n'
                    f'✅ Дата рождения: {data["date_birth"]}\n'
                    f"Место рождения:\n"
                    f"Номер паспорта (RG):\n"
                    f"Номер паспорта (CPF):\n"
                    f"Дата выдачи:\n"
                    f"Место выдачи:\n"
                    f"Фотография:\n"
                    f"Подпись:\n"
                    f"Размер документа:",
                    reply_markup=client_kb.cancelledKeyboard,
                )
                msg_delete = await bot.send_message(
                    user_id,
                    "Введите место рождения ✏️\n"
                    "Формат: Город/штат\n"
                    'Либо нажмите на кнопку "Пропустить"',
                    reply_markup=ReplyKeyboardMarkup(
                        resize_keyboard=True, one_time_keyboard=True
                    )
                    .add(KeyboardButton("Пропустить"))
                    .add(KeyboardButton("Назад ◀️")),
                )
                async with state.proxy() as data:
                    data["message_edit"] = messagetoedit["message_id"]
                    data["msg_delete"] = msg_delete["message_id"]
                await FSM.create_br_id_place_birth.set()
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Введите дату в правильном формате.\n" "Формат дд.мм.гггг",
                        reply_markup=client_kb.cancelledKeyboard,
                    )
                    data["msg_delete"] = msg_delete["message_id"]
        else:
            async with state.proxy() as data:
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                msg_delete = await bot.send_message(
                    user_id,
                    "❌ Введите дату в правильном формате.\n" "Формат дд.мм.гггг",
                    reply_markup=client_kb.cancelledKeyboard,
                )
                data["msg_delete"] = msg_delete["message_id"]


async def command_create_br_id_place_birth(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["place_birth"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f"Дата рождения:\n"
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите дату рождения ✏️\n" "Формат дд.мм.гггг",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_date_birth.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        async with state.proxy() as data:
            data["place_birth"] = message.text
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер паспорта (RG) ✏️\n" "Формат числовой: xx.xxx.xxx-x",
            reply_markup=kb,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_pass_number.set()


async def command_create_br_id_pass_number_generate(
    message: types.Message, state: FSMContext
):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["pass_number"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите место рождения ✏️\n"
            "Формат: Город/штат\n"
            'Либо нажмите на кнопку "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_place_birth.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["pass_number"] = "Автоматическая генерация"
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер паспорта (CPF) ✏️\n" "Формат числовой: xxx.xxx.xxx-xx",
            reply_markup=kb,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_pass_number_cpf.set()


async def command_create_br_id_pass_number(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["pass_number"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f"Место рождения:\n"
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите место рождения ✏️\n"
            "Формат: Город/штат\n"
            'Либо нажмите на кнопку "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_place_birth.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["pass_number"] = message.text
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер паспорта (CPF) ✏️\n" "Формат числовой: xxx.xxx.xxx-xx",
            reply_markup=kb,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_pass_number_cpf.set()


async def command_create_br_id_pass_number_cpf_generate(
    message: types.Message, state: FSMContext
):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["pass_number_cpf"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["pass_number"] = message.text
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
        )

        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер паспорта (RG) ✏️\n" "Формат числовой: xx.xxx.xxx-x",
            reply_markup=kb,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_pass_number.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["pass_number_cpf"] = "Автоматическая генерация"
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите дату выдачи документа ✏️\n"
            "Не менее 05.04.2006.\n"
            "Формат дд.мм.гггг",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_date_doc.set()


async def command_create_br_id_pass_number_cpf(
    message: types.Message, state: FSMContext
):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["pass_number_cpf"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["pass_number"] = message.text
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f"Номер паспорта (RG):\n"
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер паспорта (RG) ✏️\n" "Формат числовой: xx.xxx.xxx-x",
            reply_markup=kb,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_pass_number.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["pass_number_cpf"] = message.text
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите дату выдачи документа ✏️\n"
            "Не менее 05.04.2006.\n"
            "Формат дд.мм.гггг",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_date_doc.set()


async def command_create_br_id_date_doc(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["date_doc"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f"Номер паспорта (CPF):\n"
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
        )
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер паспорта (CPF) ✏️\n" "Формат числовой: xxx.xxx.xxx-xx",
            reply_markup=kb,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_pass_number_cpf.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        if (
            len(msg) == 10
            and msg[2] == "."
            and msg[5] == "."
            and msg[:2].isdigit()
            and msg[3:5].isdigit()
            and msg[6:].isdigit()
            and compare_date("05.04.2006", message.text)
        ):
            if int(msg[:2]) <= 31 and int(msg[3:5]) <= 12:
                async with state.proxy() as data:
                    data["date_doc"] = message.text
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["message_edit"]
                    )
                except:
                    pass
                messagetoedit = await bot.send_message(
                    user_id,
                    f"Данные клиента\n"
                    f'✅ Имя: {data["name"]}\n'
                    f'✅ Фамилия: {data["family"]}\n'
                    f'✅ ФИО отца: {data["name_father"]}\n'
                    f'✅ ФИО матери: {data["name_mother"]}\n'
                    f'✅ Дата рождения: {data["date_birth"]}\n'
                    f'✅ Место рождения: {data["place_birth"]}\n'
                    f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
                    f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
                    f'✅ Дата выдачи: {data["date_doc"]}\n'
                    f"Место выдачи:\n"
                    f"Фотография:\n"
                    f"Подпись:\n"
                    f"Размер документа:",
                    reply_markup=client_kb.cancelledKeyboard,
                )
                msg_delete = await bot.send_message(
                    user_id,
                    "Введите место выдачи документа ✏️\n"
                    'Либо нажмите на кнопку "Пропустить"',
                    reply_markup=ReplyKeyboardMarkup(
                        resize_keyboard=True, one_time_keyboard=True
                    )
                    .add(KeyboardButton("Пропустить"))
                    .add(KeyboardButton("Назад ◀️")),
                )
                async with state.proxy() as data:
                    data["message_edit"] = messagetoedit["message_id"]
                    data["msg_delete"] = msg_delete["message_id"]
                await FSM.create_br_id_place_doc.set()
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Введите дату в правильном формате.\n" "Формат дд.мм.гггг",
                        reply_markup=client_kb.cancelledKeyboard,
                    )
                    data["msg_delete"] = msg_delete["message_id"]
        else:
            async with state.proxy() as data:
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                msg_delete = await bot.send_message(
                    user_id,
                    "❌ Введите дату в правильном формате.\n" "Формат дд.мм.гггг",
                    reply_markup=client_kb.cancelledKeyboard,
                )
                data["msg_delete"] = msg_delete["message_id"]


async def command_create_br_id_place_doc(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["place_doc"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f"Дата выдачи:\n"
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите дату выдачи документа ✏️\n"
            "Не менее 05.04.2006.\n"
            "Формат дд.мм.гггг",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_date_doc.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            data["place_doc"] = message.text
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f'✅ Дата выдачи: {data["date_doc"]}\n'
            f'✅ Место выдачи: {data["place_doc"]}\n'
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Загрузите фотографию 📷\n"
            " ❗️Требования к фотографии:\n"
            "➖ Фотография должна быть загружена без сжатия, нажимаем скрепку - файл - выбрать фото;\n"
            "➖ На фотографии должно быть видно плечи, глаза открыты;\n"
            "➖ Кадр должен быть в хорошем освещении;\n"
            "➖ Лицо должно быть под прямым углом к камере;\n"
            "Поддерживаемые форматы: JPG, JPEG, PNG ❗️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_photo.set()


async def command_create_br_id_photo(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["photo"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f'✅ Дата выдачи: {data["date_doc"]}\n'
            f"Место выдачи:\n"
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите место выдачи документа ✏️\n" 'Либо нажмите на кнопку "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_place_doc.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        async with state.proxy() as data:
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
        if message.document:
            if message.document["mime_type"] == "image/png":
                message_wait1 = await bot.send_message(
                    user_id, "Подождите, фотография обрабатывается"
                )
                async with state.proxy() as data:
                    data["message_wait1"] = message_wait1["message_id"]
                await bot.download_file_by_id(
                    file_id=message.document.file_id,
                    destination=f"./files/br_pass/br_id/photo_usr/{message.from_user.id}.png",
                    timeout=60,
                )
                try:
                    async with state.proxy() as data:
                        thr = threading.Thread(
                            target=process_check_image_id,
                            args=(user_id, data),
                            name=f"thr-{user_id}",
                        )
                        thr.start()
                        while thr.is_alive():
                            await asyncio.sleep(1)
                        async with state.proxy() as data:
                            data["photo"] = message.document.file_id
                            try:
                                await bot.delete_message(
                                    chat_id=message.from_user.id,
                                    message_id=data["message_wait1"],
                                )
                            except:
                                pass
                            try:
                                await bot.delete_message(
                                    chat_id=message.from_user.id,
                                    message_id=data["message_edit"],
                                )
                            except:
                                pass
                        messagetoedit = await bot.send_message(
                            user_id,
                            f"Данные клиента\n"
                            f'✅ Имя: {data["name"]}\n'
                            f'✅ Фамилия: {data["family"]}\n'
                            f'✅ ФИО отца: {data["name_father"]}\n'
                            f'✅ ФИО матери: {data["name_mother"]}\n'
                            f'✅ Дата рождения: {data["date_birth"]}\n'
                            f'✅ Место рождения: {data["place_birth"]}\n'
                            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
                            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
                            f'✅ Дата выдачи: {data["date_doc"]}\n'
                            f'✅ Место выдачи: {data["place_doc"]}\n'
                            f"✅ Фотография:\n"
                            f"Подпись:\n"
                            f"Размер документа:",
                            reply_markup=client_kb.cancelledKeyboard,
                        )
                        async with state.proxy() as data:
                            data["message_edit"] = messagetoedit["message_id"]
                        async with aiofiles.open(
                            f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png",
                            "rb",
                        ) as choose_signature_go:
                            msg_delete = await bot.send_photo(
                                user_id,
                                photo=choose_signature_go,
                                caption="Выберите подпись, либо нажмите "
                                '"Пропустить" чтобы оставить поле пустым',
                                reply_markup=client_kb.kb_inline_br_pass_signature,
                            )
                        async with state.proxy() as data:
                            data["msg_delete"] = msg_delete["message_id"]
                        await FSM.create_br_id_signature.set()
                except Exception as ex:
                    print("ошибка фото br id : ", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["message_wait1"],
                            )
                        except:
                            pass
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "❌ Фотография не соответствует требованиям.\n"
                            "ИИ не смог обработать вашу фотографию.\n"
                            "Это происходит, если фото не соответствует требованиям, "
                            "проверьте что расширение файла PNG, "
                            "либо загрузите другое изображение.",
                        )
                        data["msg_delete"] = msg_delete["message_id"]

            elif message.document["mime_type"] == "image/jpeg":
                message_wait1 = await bot.send_message(
                    user_id, "Подождите, фотография обрабатывается"
                )
                async with state.proxy() as data:
                    data["message_wait1"] = message_wait1["message_id"]
                await bot.download_file_by_id(
                    file_id=message.document.file_id,
                    destination=f"./files/br_pass/br_id/photo_usr/{message.from_user.id}.jpg",
                )
                # AI work

                from rembg import remove

                out = remove(
                    Image.open(
                        f"./files/br_pass/br_id/photo_usr/{message.from_user.id}.jpg"
                    ),
                    True,
                    240,
                    240,
                )
                out = out.convert("RGBA")
                out.save(f"./files/br_pass/br_id/photo_usr/{message.from_user.id}.png")
                try:
                    async with state.proxy() as data:
                        thr = threading.Thread(
                            target=process_check_image_id,
                            args=(user_id, data),
                            name=f"thr-{user_id}",
                        )
                        thr.start()
                        while thr.is_alive():
                            await asyncio.sleep(1)
                        async with state.proxy() as data:
                            data["photo"] = message.document.file_id
                            try:
                                await bot.delete_message(
                                    chat_id=message.from_user.id,
                                    message_id=data["message_wait1"],
                                )
                            except:
                                pass
                            try:
                                await bot.delete_message(
                                    chat_id=message.from_user.id,
                                    message_id=data["message_edit"],
                                )
                            except:
                                pass
                        messagetoedit = await bot.send_message(
                            user_id,
                            f"Данные клиента\n"
                            f'✅ Имя: {data["name"]}\n'
                            f'✅ Фамилия: {data["family"]}\n'
                            f'✅ ФИО отца: {data["name_father"]}\n'
                            f'✅ ФИО матери: {data["name_mother"]}\n'
                            f'✅ Дата рождения: {data["date_birth"]}\n'
                            f'✅ Место рождения: {data["place_birth"]}\n'
                            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
                            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
                            f'✅ Дата выдачи: {data["date_doc"]}\n'
                            f'✅ Место выдачи: {data["place_doc"]}\n'
                            f"✅ Фотография:\n"
                            f"Подпись:\n"
                            f"Размер документа:",
                        )
                        async with state.proxy() as data:
                            data["message_edit"] = messagetoedit["message_id"]
                        async with aiofiles.open(
                            f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png",
                            "rb",
                        ) as choose_signature_go:
                            msg_delete = await bot.send_photo(
                                user_id,
                                photo=choose_signature_go,
                                caption="Выберите подпись, либо нажмите "
                                '"Пропустить" чтобы оставить поле пустым',
                                reply_markup=client_kb.kb_inline_uk_pass_signature,
                            )
                        async with state.proxy() as data:
                            data["msg_delete"] = msg_delete["message_id"]
                        await FSM.create_br_id_signature.set()
                except Exception as ex:
                    print("ошибка фото uk : ", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["message_wait1"],
                            )
                        except:
                            pass
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "❌ Фотография не соответствует требованиям.\n"
                            "ИИ не смог обработать вашу фотографию.\n"
                            "Это происходит, если фото не соответствует требованиям, "
                            "проверьте что расширение файла PNG, "
                            "либо загрузите другое изображение.",
                        )
                        data["msg_delete"] = msg_delete["message_id"]
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Фотография не соответствует требованиям.\n"
                        "ИИ не смог обработать вашу фотографию.\n"
                        "Это происходит, если фото не соответствует требованиям, "
                        "проверьте что расширение файла PNG, "
                        "либо загрузите другое изображение.",
                    )
                    data["msg_delete"] = msg_delete["message_id"]
        elif message.photo:
            async with state.proxy() as data:
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                msg_delete = await bot.send_message(
                    user_id,
                    "❌ Фотография должна быть загружена без сжатия, "
                    "повторите отправку корректно",
                )
                data["msg_delete"] = msg_delete["message_id"]
        else:
            async with state.proxy() as data:
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                msg_delete = await bot.send_message(
                    user_id,
                    "❌ Фотография не соответствует требованиям.\n"
                    "ИИ не смог обработать вашу фотографию.\n"
                    "Это происходит, если фото не соответствует требованиям, "
                    "проверьте что расширение файла PNG, "
                    "либо загрузите другое изображение.",
                )
                data["msg_delete"] = msg_delete["message_id"]


async def command_create_br_id_signature(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    try:
        await bot.delete_message(
            chat_id=callback.from_user.id, message_id=callback.message.message_id
        )
    except:
        pass
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
    if callback.data == "signature_pass":
        async with state.proxy() as data:
            data["signature"] = "Не ставить"
            try:
                await bot.delete_message(
                    chat_id=callback.from_user.id, message_id=data["message_edit"]
                )
            except:
                pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f'✅ Дата выдачи: {data["date_doc"]}\n'
            f'✅ Место выдачи: {data["place_doc"]}\n'
            f"✅ Фотография:\n"
            f'✅ Подпись: {data["signature"]}\n'
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
        msg_delete = await bot.send_message(
            user_id, f"Выберите размер документа", reply_markup=client_kb.kb_br_id_size
        )
        async with state.proxy() as data:
            data["msg_delete"] = msg_delete["message_id"]
            await FSM.create_br_id_size.set()
    else:
        async with state.proxy() as data:
            signatire = str(callback.data[10:])
            data["signature"] = signatire
            try:
                await bot.delete_message(
                    chat_id=callback.from_user.id, message_id=data["message_edit"]
                )
            except:
                pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f'✅ Дата выдачи: {data["date_doc"]}\n'
            f'✅ Место выдачи: {data["place_doc"]}\n'
            f"✅ Фотография:\n"
            f'✅ Подпись: {data["signature"]}\n'
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
        msg_delete = await bot.send_message(
            user_id, f"Выберите размер документа", reply_markup=client_kb.kb_br_id_size
        )
        async with state.proxy() as data:
            data["msg_delete"] = msg_delete["message_id"]
            await FSM.create_br_id_size.set()


async def command_create_br_id_size(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    async with state.proxy() as data:
        data["size"] = None
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ ФИО отца: {data["name_father"]}\n'
            f'✅ ФИО матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f'✅ Дата выдачи: {data["date_doc"]}\n'
            f'✅ Место выдачи: {data["place_doc"]}\n'
            f"Фотография:\n"
            f"Подпись:\n"
            f"Размер документа:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Загрузите фотографию 📷\n"
            " ❗️Требования к фотографии:\n"
            "➖ Фотография должна быть загружена без сжатия, нажимаем скрепку - файл - выбрать фото;\n"
            "➖ На фотографии должно быть видно плечи, глаза открыты;\n"
            "➖ Кадр должен быть в хорошем освещении;\n"
            "➖ Лицо должно быть под прямым углом к камере;\n"
            "Поддерживаемые форматы: JPG, JPEG, PNG ❗️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_br_id_photo.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        if (
            msg == "📄 На листе A4"
            or msg == "🪪 В размер документа"
            or msg == "🖼 На фоне"
        ):
            async with state.proxy() as data:
                data["size"] = str(msg[2:])
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["message_edit"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Имя: {data["name"]}\n'
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ ФИО отца: {data["name_father"]}\n'
                f'✅ ФИО матери: {data["name_mother"]}\n'
                f'✅ Дата рождения: {data["date_birth"]}\n'
                f'✅ Место рождения: {data["place_birth"]}\n'
                f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
                f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
                f'✅ Дата выдачи: {data["date_doc"]}\n'
                f'✅ Место выдачи: {data["place_doc"]}\n'
                f"✅ Фотография:\n"
                f'✅ Подпись: {data["signature"]}\n'
                f'✅ Размер документа: {data["size"]}',
            )
            msg_delete = await bot.send_message(
                user_id,
                "Ожидайте генерируется...",
                reply_markup=client_kb.cancelledKeyboard,
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_id,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png",
                        "rb",
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_br_finish_id,
                    )
                    try:
                        await messagetoedit.delete()
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_br_id.set()
                except Exception as ex:
                    print("Ошибка в генерации br id:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_br_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_br_id.set()
        else:
            async with state.proxy() as data:
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                msg_delete = await bot.send_message(
                    user_id,
                    "❌ Недопустимое значение\n " "Нажмите на кнопку ниже",
                    reply_markup=client_kb.kb_br_id_size,
                )
                data["msg_delete"] = msg_delete["message_id"]


async def command_change_br_id(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    try:
        await bot.delete_message(
            chat_id=callback.from_user.id, message_id=callback.message.message_id
        )
    except:
        pass
    msg_delete = await bot.send_message(
        user_id,
        "Выберите параметр, который хотите изменить",
        reply_markup=client_kb.kb_br_change_go_id,
    )
    async with state.proxy() as data:
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_what.set()


async def command_change_br_id_name(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите имя ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "name"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_family(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите фамилию ✏️", reply_markup=client_kb.cancelledKeyboard
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "family"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_name_father(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
    kb.add(types.KeyboardButton("Назад ◀️"), types.KeyboardButton("Пропустить"))
    msg_delete = await bot.send_message(user_id, "Введите ФИО отца ✏️", reply_markup=kb)
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "name_father"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_name_mother(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(user_id, "Введите ФИО матери ✏️")
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "name_mother"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_date_birth(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Введите дату рождения ✏️\n" "Формат дд.мм.гггг",
        reply_markup=client_kb.cancelledKeyboard,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "date_birth"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_place_birth(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Введите место рождения ✏️\n"
        "Формат: Город/штат\n"
        'Либо нажмите на кнопку "Пропустить"',
        reply_markup=client_kb.kb_skip,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "place_birth"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_pass_number(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
    kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
    msg_delete = await bot.send_message(
        user_id,
        "Введите номер паспорта (RG) ✏️\n" "Формат числовой: xx.xxx.xxx-x",
        reply_markup=kb,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "pass_number"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_pass_number_cpf(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
    kb.add(types.KeyboardButton("Сгенерировать"), types.KeyboardButton("Назад ◀️"))
    msg_delete = await bot.send_message(
        user_id,
        "Введите номер паспорта (CPF) ✏️\n" "Формат числовой: xxx.xxx.xxx-xx",
        reply_markup=kb,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "pass_number_cpf"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_date_doc(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Введите дату выдачи документа ✏️\n"
        "Не менее 05.04.2006.\n"
        "Формат дд.мм.гггг",
        reply_markup=client_kb.cancelledKeyboard,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "date_doc"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_place_doc(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Введите место выдачи документа ✏️\n" 'Либо нажмите на кнопку "Пропустить"',
        reply_markup=client_kb.kb_skip,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "place_doc"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_photo(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Загрузите фотографию 📷\n"
        " ❗️Требования к фотографии:\n"
        "➖ Фотография должна быть загружена без сжатия, нажимаем скрепку - файл - выбрать фото;\n"
        "➖ На фотографии должно быть видно плечи, глаза открыты;\n"
        "➖ Кадр должен быть в хорошем освещении;\n"
        "➖ Лицо должно быть под прямым углом к камере;\n"
        "Поддерживаемые форматы: JPG, JPEG, PNG ❗️",
        reply_markup=client_kb.cancelledKeyboard,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "photo"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_signature(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    async with state.proxy() as data:
        thr = threading.Thread(
            target=process_change_signature, args=(user_id, data), name=f"thr-{user_id}"
        )
        thr.start()
        while thr.is_alive():
            await asyncio.sleep(1)
        async with aiofiles.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png", "rb"
        ) as choose_signature_go:
            msg_delete = await bot.send_photo(
                user_id,
                photo=choose_signature_go,
                caption="Выберите подпись, либо нажмите "
                '"Пропустить" чтобы оставить поле пустым',
                reply_markup=client_kb.kb_inline_br_pass_signature,
            )
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "signature"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_size(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, f"Выберите размер документа", reply_markup=client_kb.kb_br_id_size
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "size"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_br_id_go.set()


async def command_change_br_id_go(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    try:
        await bot.delete_message(
            chat_id=message.from_user.id, message_id=message.message_id
        )
    except:
        pass
    async with state.proxy() as data:
        if data["what_change"] == "name":
            async with state.proxy() as data:
                data["name"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            await handler_generating_id(user_id, state)
        elif data["what_change"] == "family":
            async with state.proxy() as data:
                data["family"] = msg
                data["sign"] = data["family"].capitalize()
                if is_portuguese(data["sign"]):
                    data["sign"] = pt_transliterate(data["sign"])
                if len(data["sign"]) > 5:
                    data["sign"] = data["sign"][: random.randint(3, 5)]
                await state.update_data(sign=data["sign"])
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            await handler_generating_id(user_id, state)
        elif data["what_change"] == "name_father":
            async with state.proxy() as data:
                data["name_father"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            await handler_generating_id(user_id, state)
        elif data["what_change"] == "name_mother":
            async with state.proxy() as data:
                data["name_mother"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            await handler_generating_id(user_id, state)
        elif data["what_change"] == "date_birth":
            if (
                len(msg) == 10
                and msg[2] == "."
                and msg[5] == "."
                and msg[:2].isdigit()
                and msg[3:5].isdigit()
                and msg[6:].isdigit()
            ):
                if int(msg[:2]) <= 31 and int(msg[3:5]) <= 12:
                    async with state.proxy() as data:
                        data["date_birth"] = message.text
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id,
                            message_id=data["message_edit"],
                        )
                    except:
                        pass
                    await handler_generating_id(user_id, state)
                else:
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "❌ Введите дату в правильном формате.\n"
                            "Формат дд.мм.гггг",
                            reply_markup=client_kb.cancelledKeyboard,
                        )
                        data["msg_delete"] = msg_delete["message_id"]
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Введите дату в правильном формате.\n" "Формат дд.мм.гггг",
                        reply_markup=client_kb.cancelledKeyboard,
                    )
                    data["msg_delete"] = msg_delete["message_id"]
        elif data["what_change"] == "place_birth":
            async with state.proxy() as data:
                data["place_birth"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            await handler_generating_id(user_id, state)
        elif data["what_change"] == "pass_number":
            if msg == "Сгeнeрировать":
                async with state.proxy() as data:
                    data["pass_number"] = "Автоматическая генерация"
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=message.message_id
                        )
                    except:
                        pass
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await handler_generating_id(user_id, state)
            else:
                async with state.proxy() as data:
                    data["pass_number"] = msg
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=message.message_id
                    )
                except:
                    pass
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                await handler_generating_id(user_id, state)
        elif data["what_change"] == "pass_number_cpf":
            if msg == "Сгeнeрировать":
                async with state.proxy() as data:
                    data["pass_number_cpf"] = "Автоматическая генерация"
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=message.message_id
                        )
                    except:
                        pass
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await handler_generating_id(user_id, state)
            else:
                async with state.proxy() as data:
                    data["pass_number_cpf"] = msg
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=message.message_id
                    )
                except:
                    pass
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                await handler_generating_id(user_id, state)
        elif data["what_change"] == "date_doc":
            if (
                len(msg) == 10
                and msg[2] == "."
                and msg[5] == "."
                and msg[:2].isdigit()
                and msg[3:5].isdigit()
                and msg[6:].isdigit()
            ):
                if int(msg[:2]) <= 31 and int(msg[3:5]) <= 12:
                    async with state.proxy() as data:
                        data["date_doc"] = message.text
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id,
                            message_id=data["message_edit"],
                        )
                    except:
                        pass
                    await handler_generating_id(user_id, state)
                else:
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "❌ Введите дату в правильном формате.\n"
                            "Формат дд.мм.гггг",
                            reply_markup=client_kb.cancelledKeyboard,
                        )
                        data["msg_delete"] = msg_delete["message_id"]
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Введите дату в правильном формате.\n" "Формат дд.мм.гггг",
                        reply_markup=client_kb.cancelledKeyboard,
                    )
                    data["msg_delete"] = msg_delete["message_id"]
        elif data["what_change"] == "place_doc":
            async with state.proxy() as data:
                data["place_doc"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            await handler_generating_id(user_id, state)
        elif data["what_change"] == "photo":
            if message.document:
                if message.document["mime_type"] == "image/png":
                    message_wait1 = await bot.send_message(
                        user_id, "Подождите, фотография обрабатывается"
                    )
                    async with state.proxy() as data:
                        data["message_wait1"] = message_wait1["message_id"]
                    await bot.download_file_by_id(
                        file_id=message.document.file_id,
                        destination=f"./files/br_pass/br_id/photo_usr/{message.from_user.id}.png",
                    )
                    try:
                        async with state.proxy() as data:
                            thr = threading.Thread(
                                target=process_check_image_id,
                                args=(user_id, data),
                                name=f"thr-{user_id}",
                            )
                            thr.start()
                            while thr.is_alive():
                                await asyncio.sleep(1)
                            async with state.proxy() as data:
                                data["photo"] = message.document.file_id
                                try:
                                    await bot.delete_message(
                                        chat_id=message.from_user.id,
                                        message_id=data["message_wait1"],
                                    )
                                except:
                                    pass
                                try:
                                    await bot.delete_message(
                                        chat_id=message.from_user.id,
                                        message_id=data["message_edit"],
                                    )
                                except:
                                    pass
                            await handler_generating_id(user_id, state)
                    except Exception as ex:
                        print("123ошибка фото br id : ", ex)
                        async with state.proxy() as data:
                            try:
                                await bot.delete_message(
                                    chat_id=message.from_user.id,
                                    message_id=data["message_wait1"],
                                )
                            except:
                                pass
                            try:
                                await bot.delete_message(
                                    chat_id=message.from_user.id,
                                    message_id=data["msg_delete"],
                                )
                            except:
                                pass
                            msg_delete = await bot.send_message(
                                user_id,
                                "❌ Фотография не соответствует требованиям.\n"
                                "ИИ не смог обработать вашу фотографию.\n"
                                "Это происходит, если фото не соответствует требованиям, "
                                "проверьте что расширение файла PNG, "
                                "либо загрузите другое изображение.",
                            )
                            data["msg_delete"] = msg_delete["message_id"]
                else:
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "❌ Фотография не соответствует требованиям.\n"
                            "ИИ не смог обработать вашу фотографию.\n"
                            "Это происходит, если фото не соответствует требованиям, "
                            "проверьте что расширение файла PNG, "
                            "либо загрузите другое изображение.",
                        )
                        data["msg_delete"] = msg_delete["message_id"]
            elif message.photo:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Фотография должна быть загружена без сжатия, "
                        "повторите отправку корректно",
                    )
                    data["msg_delete"] = msg_delete["message_id"]
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Фотография не соответствует требованиям.\n"
                        "ИИ не смог обработать вашу фотографию.\n"
                        "Это происходит, если фото не соответствует требованиям, "
                        "проверьте что расширение файла PNG, "
                        "либо загрузите другое изображение.",
                    )
                    data["msg_delete"] = msg_delete["message_id"]
        elif data["what_change"] == "size":
            if (
                msg == "📄 На листе A4"
                or msg == "🪪 В размер документа"
                or msg == "🖼 На фоне"
            ):
                async with state.proxy() as data:
                    data["size"] = str(msg[2:])
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                try:
                    await bot.delete_message(
                        chat_id=message.from_user.id, message_id=data["message_edit"]
                    )
                except:
                    pass
                await handler_generating_id(user_id, state)
            else:
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "❌ Недопустимое значение\n " "Нажмите на кнопку ниже",
                        reply_markup=client_kb.kb_br_id_size,
                    )
                    data["msg_delete"] = msg_delete["message_id"]


async def command_change_br_id_go_inline(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    try:
        await bot.delete_message(
            chat_id=callback.from_user.id, message_id=callback.message.message_id
        )
    except:
        pass
    async with state.proxy() as data:
        if data["what_change"] == "signature":
            if callback.data == "signature_pass":
                async with state.proxy() as data:
                    data["signature"] = "Не ставить"
                try:
                    await bot.delete_message(
                        chat_id=callback.from_user.id, message_id=data["message_edit"]
                    )
                except:
                    pass
                await handler_generating_id(user_id, state)
            else:
                signatire = str(callback.data[10:])
                async with state.proxy() as data:
                    data["signature"] = signatire
                try:
                    await bot.delete_message(
                        chat_id=callback.from_user.id, message_id=data["message_edit"]
                    )
                except:
                    pass
                await handler_generating_id(user_id, state)


async def command_pay_br_id(callback: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data["pay_country"] = "br_id"
    await client.command_promo_quest(callback, state)


def process_check_image_id(user_id, data):
    try:
        img = cv2.imread(
            f"./files/br_pass/br_id/photo_usr/{user_id}.png", cv2.IMREAD_UNCHANGED
        )
        face_cascade = cv2.CascadeClassifier(
            "./data/haarcascade_frontalface_default.xml"
        )
        faces = face_cascade.detectMultiScale(img, 1.2, 5)
        if len(faces) != 0:
            (x, y, w, h) = faces[0]
            h_top = int(h * 0.4)
            h_bottom = int(h * 0.3)
            w_left = int(w * 0.2)
            w_right = int(w * 0.2)
            x_left = max(0, x - w_left)
            x_right = min(img.shape[1], x + w + w_right)
            w_new = x_right - x_left
            y_top = max(0, y - h_top)
            y_bottom = min(img.shape[0], y + h + h_bottom)
            h_new = y_bottom - y_top

            cropped_img = img[y_top : y_top + h_new, x_left : x_left + w_new]
            resized_img = cv2.resize(
                cropped_img, None, fx=2, fy=2, interpolation=cv2.INTER_AREA
            )
            cv2.imwrite(f"./files/br_pass/br_id/photo_usr/{user_id}.png", resized_img)
            inputt = Image.open(f"./files/br_pass/br_id/photo_usr/{user_id}.png")
            print(inputt.size)

            baseheght = 264
            wpercent = baseheght / float(inputt.size[1])
            wsize = int((float(inputt.size[0]) * float(wpercent)))
            img = inputt.resize((wsize, baseheght))
            output = img
            output = output.rotate(-90, expand=True)
            output.save(f"./files/br_pass/br_id/photo_usr/{user_id}.png")
        else:
            try:
                os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}.png")
            except:
                pass
            try:
                os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png")
            except:
                pass
            try:
                os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png")
            except:
                pass
            try:
                os.remove(
                    f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png"
                )
            except:
                pass
            return
        text = data["sign"].capitalize()
        if is_portuguese(text):
            text = pt_transliterate(text)
        txt = Image.new("RGBA", (1800, 600), (255, 255, 255, 0))
        go_txt = ImageDraw.Draw(txt)
        fnt1 = ImageFont.truetype("./fonts/1.ttf", size=270)
        go_txt.text(xy=(200, 50), text=f"{text}", font=fnt1, fill="#000000")
        fnt2 = ImageFont.truetype("./fonts/2.ttf", size=190)
        go_txt.text(
            xy=(800, 50), text=f"{text}", font=fnt2, fill="#000000", stroke_width=1
        )
        fnt3 = ImageFont.truetype("./fonts/3.ttf", size=200)
        go_txt.text(
            xy=(1400, 50), text=f"{text}", font=fnt3, fill="#000000", stroke_width=1
        )
        fnt4 = ImageFont.truetype("./fonts/4.ttf", size=100)
        go_txt.text(
            xy=(200, 400), text=f"{text}", font=fnt4, fill="#000000", stroke_width=1
        )
        fnt5 = ImageFont.truetype("./fonts/5.ttf", size=150)
        go_txt.text(
            xy=(800, 400), text=f"{text}", font=fnt5, fill="#000000", stroke_width=1
        )
        fnt6 = ImageFont.truetype("./fonts/6.ttf", size=80)
        go_txt.text(xy=(1400, 400), text=f"{text}", font=fnt6, fill="#000000")
        fnt66 = ImageFont.truetype("./fonts/66.ttf", size=80)
        go_txt.text(xy=(1430, 440), text=f"k", font=fnt66, fill="#000000")
        txt_blur = txt.filter(ImageFilter.GaussianBlur(radius=1))
        holst = Image.new("RGBA", (1800, 600), (255, 255, 255, 255))
        choose_signature = Image.alpha_composite(holst, txt_blur)
        choose_signature.save(
            f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png"
        )
    except Exception as ex:
        print("ошибка process_check_image_br: ", ex)
        try:
            os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png")
        except:
            pass
        try:
            os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png")
        except:
            pass
        try:
            os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png")
        except:
            pass


def process_generate_id(user_id, data):
    try:
        os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png")
    except:
        pass
    try:
        print(data)
        doc = Image.open("./files/br_pass/br_id/id.png").convert("RGBA")
        layer_for_photos = Image.new("RGBA", doc.size, (0, 0, 0, 0))
        photo_usr = Image.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}.png"
        ).convert("RGBA")
        layer_for_photos.paste(photo_usr, (845, 759))
        finger_path = "./files/br_pass/br_id/fingerprints"
        files = os.listdir(finger_path)
        kol_files = len(files)
        number_files_finger = random.randint(1, int(kol_files))
        fingerprint = Image.open(
            f"./files/br_pass/br_id/fingerprints/{number_files_finger}.png"
        ).convert("RGBA")
        layer_for_photos.paste(fingerprint, (554, 798))
        result = Image.alpha_composite(doc, layer_for_photos)

        # ниже подпись
        sign = data["sign"].capitalize()
        if is_portuguese(sign):
            sign = pt_transliterate(sign)
        if data["signature"] != "Не ставить":
            text = sign
            txt_signature = Image.new("RGBA", result.size, (255, 255, 255, 0))
            go_txt_signature = ImageDraw.Draw(txt_signature)
            if data["signature"] == "1":
                fnt1 = ImageFont.truetype("./fonts/1.ttf", size=140)
                go_txt_signature.text(
                    xy=(
                        850 - (fnt1.getbbox(text)[2] - fnt1.getbbox(text)[0]) // 2,
                        980,
                    ),
                    text=f"{text}",
                    font=fnt1,
                    fill="#000000",
                )
            elif data["signature"] == "2":
                fnt2 = ImageFont.truetype("./fonts/2.ttf", size=70)
                go_txt_signature.text(
                    xy=(
                        850 - (fnt2.getbbox(text)[2] - fnt2.getbbox(text)[0]) // 2,
                        985,
                    ),
                    text=f"{text}",
                    font=fnt2,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "3":
                fnt3 = ImageFont.truetype("./fonts/3.ttf", size=100)
                go_txt_signature.text(
                    xy=(
                        850 - (fnt3.getbbox(text)[2] - fnt3.getbbox(text)[0]) // 2,
                        985,
                    ),
                    text=f"{text}",
                    font=fnt3,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "4":
                fnt4 = ImageFont.truetype("./fonts/4.ttf", size=40)
                go_txt_signature.text(
                    xy=(
                        850 - (fnt4.getbbox(text)[2] - fnt4.getbbox(text)[0]) // 2,
                        1000,
                    ),
                    text=f"{text}",
                    font=fnt4,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "5":
                fnt5 = ImageFont.truetype("./fonts/5.ttf", size=70)
                go_txt_signature.text(
                    xy=(
                        850 - (fnt5.getbbox(text)[2] - fnt5.getbbox(text)[0]) // 2,
                        1000,
                    ),
                    text=f"{text}",
                    font=fnt5,
                    fill="#000000",
                    stroke_width=0,
                )
            elif data["signature"] == "6":
                fnt6 = ImageFont.truetype("./fonts/6.ttf", size=40)
                go_txt_signature.text(
                    xy=(
                        850 - (fnt6.getbbox(text)[2] - fnt6.getbbox(text)[0]) // 2,
                        1000,
                    ),
                    text=f"{text}",
                    font=fnt6,
                    fill="#000000",
                )
            txt_blur = txt_signature.filter(ImageFilter.GaussianBlur(radius=1))

            # txt_blur = txt_signature
            result = Image.alpha_composite(result, txt_blur)

        txt = Image.new("RGBA", result.size, (255, 255, 255, 0))
        fnt_ocrb = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=18
        )
        fnt_ocrb_one = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=20
        )
        fnt_ocrb_two = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=17
        )
        fnt_ocrb_two_cpf = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=16
        )
        fnt_ocrb_three = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=19
        )
        fnt_meyro = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=16
        )
        fnt_arial = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/ariblk.ttf", size=14
        )
        fnt_ocr_bold = ImageFont.truetype(
            "./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=26
        )
        go_txt = ImageDraw.Draw(txt)

        # go_txt.text(xy=(800, 740), text=f"0000",
        #                    font=fnt_arial,
        #                    fill=(55, 58, 55, 255))

        # random_4_c = random.randint(1000, 9999)
        # layer_4_c = Image.new('RGBA', (50, 50), (255, 255, 255, 0))
        # text_image_4_c = ImageDraw.Draw(layer_4_c)

        # Создать пустое изображение для текста
        # random_4_c = '0000'
        random_4_c = f"0{str(random.randint(100, 999))}"
        mrz_layer = Image.new("RGBA", result.size, (255, 255, 255, 0))
        text_width, text_height = go_txt.textsize(str(random_4_c), fnt_arial)
        text_image_mrz = Image.new(
            "RGBA", (text_width + 100, text_height + 100), (255, 255, 255, 0)
        )
        text_draw_mrz = ImageDraw.Draw(text_image_mrz)
        text_draw_mrz.text(
            xy=(0, 0), text=f"{random_4_c}", font=fnt_arial, fill=(55, 58, 55, 255)
        )

        new_height_mrz = int(text_image_mrz.height) + 20
        rr_mrz = text_image_mrz.resize((text_image_mrz.width, new_height_mrz))
        rr_mrz = rr_mrz.rotate(-90, expand=True, resample=Image.BICUBIC)

        mrz_layer.paste(rr_mrz, (696, 852))
        # mrz_layer.paste(text_image_mrz, (100, 2247))
        result = Image.alpha_composite(result, mrz_layer)
        go_txt.text(
            xy=(1072, 1572),
            text=random_4_c,
            font=fnt_ocrb_two_cpf,
            fill=(44, 42, 29, 255),
        )

        shag = 1
        text_place_b = f"{data['name'].upper()} {data['family'].upper()}"
        go_txt.text(
            xy=(532, 1295), text=text_place_b, font=fnt_ocr_bold, fill=(44, 42, 29, 255)
        )
        # w = fnt_ocr_bold.getsize(f"{text_place_b[0]}")[0]
        # for bbrva in text_place_b:
        #     go_txt.text(xy=((450 + w * shag) * 1.05, 1295), text=bbrva, font=fnt_ocr_bold,
        #                 fill=(44, 42, 29, 255))
        #     shag += 1
        # # go_txt.text(xy=(541, 1295), text=f"{str(data['name']).upper()}", font=fnt_ocrb,
        # #             fill=(44, 42, 29, 255))

        shag = 1
        if data["name_father"] != "Пропустить":
            text_place_b = f"{data['name_father'].upper()}"
            w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((450 + w * shag) * 1.17, 1355),
                    text=bbrva,
                    font=fnt_ocrb,
                    fill=(44, 42, 29, 255),
                )
                shag += 1
            # go_txt.text(xy=(541, 1355), text=f"{str(data['name_father']).upper()}", font=fnt_ocrb,
            #             fill=(44, 42, 29, 255))
        else:
            pass

        shag = 1
        text_place_b = f"{data['name_mother'].upper()}"
        w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
        for bbrva in text_place_b:
            go_txt.text(
                xy=((450 + w * shag) * 1.17, 1393),
                text=bbrva,
                font=fnt_ocrb,
                fill=(44, 42, 29, 255),
            )
            shag += 1
        # go_txt.text(xy=(540, 1393), text=f"{str(data['name_mother']).upper()}", font=fnt_ocrb,
        #             fill=(44, 42, 29, 255))

        # #############################
        shag = 1
        if data["place_birth"] == "Пропустить":
            text_place_b = f"RIO DE JANEIRO/RJ".upper()
            w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((450 + w * shag) * 1.17, 1451),
                    text=bbrva,
                    font=fnt_ocrb_three,
                    fill=(44, 42, 29, 255),
                )
                shag += 1
        else:
            text_place_b = f"{data['place_birth']}".upper()
            w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((450 + w * shag) * 1.17, 1451),
                    text=bbrva,
                    font=fnt_ocrb_three,
                    fill=(44, 42, 29, 255),
                )
                shag += 1

        shag = 1
        if data["place_doc"] == "Пропустить":
            text_pic = Image.open(f"./files/br_pass/br_id/doc_origem.png").convert(
                "RGBA"
            )
            result = Image.alpha_composite(result, text_pic)
        else:
            text_place_b = f"{data['place_doc']}".upper()
            w = fnt_meyro.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((460 + w * shag) * 1.14, 1493),
                    text=bbrva,
                    font=fnt_meyro,
                    fill=(44, 42, 29, 255),
                )
                shag += 1

        # shag = 1
        # text_place_b = f"rio  de  janeiro".upper()
        # w = fnt_meyro.getsize(f"{text_place_b[0]}")[0]
        # for bbrva in text_place_b:
        #     go_txt.text(xy=((450 + w * shag) * 1.12, 1513), text=bbrva, font=fnt_meyro,
        #                 fill=(44, 42, 29, 255))
        #     shag += 1
        # # go_txt.text(xy=(536, 1513), text=f"rio  de  janeiro".upper(), font=fnt_meyro,
        # #                 fill=(44, 42, 29, 255))
        #############################

        if data["pass_number"] == "Автоматическая генерация":
            label = f"09.{random.randint(100, 999)}.{random.randint(100, 999)}-{random.randint(0, 9)}"
        else:
            label = f"{data['pass_number']}"
        go_txt.text(
            xy=(617, 1233), text=f"{label}", font=fnt_ocr_bold, fill=(44, 42, 29, 255)
        )
        if data["pass_number_cpf"] == "Автоматическая генерация":
            label_cpf = f"070.{random.randint(100, 999)}.{random.randint(100, 999)}-{random.randint(10, 99)}"
        else:
            label_cpf = f"{data['pass_number_cpf']}"
        shag = 1
        text_place_b = f"{label_cpf}".upper()
        w = fnt_ocrb_two.getsize(f"{text_place_b[0]}")[0]
        for bbrva in text_place_b:
            go_txt.text(
                xy=((430 + w * shag) * 1.23, 1547),
                text=bbrva,
                font=fnt_ocrb_two_cpf,
                fill=(44, 42, 29, 255),
            )
            shag += 1
        # go_txt.text(xy=(541, 1547), text=f"{label_cpf}",
        #             font=fnt_ocrb_two,
        #             fill=(44, 42, 29, 255))

        date_doc = data["date_doc"]
        go_txt.text(
            xy=(984, 1235),
            text=f"{date_doc[:2]}/{date_doc[3:5]}/{date_doc[6:10]}",
            font=fnt_ocrb_one,
            fill=(44, 42, 29, 255),
        )
        birth = data["date_birth"]
        go_txt.text(
            xy=(948, 1450),
            text=f"{birth[:2]}/{birth[3:5]}/{birth[6:10]}",
            font=fnt_ocrb_one,
            fill=(44, 42, 29, 255),
        )
        result = Image.alpha_composite(result, txt)

        result.save(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png"
        )
        # Добавляем зернистость
        img = cv2.imread(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png",
            cv2.IMREAD_UNCHANGED,
        )
        kernel_noise = np.zeros((3, 3), np.uint8)
        kernel_noise[1][1] = 1
        kernel_noise[1][2] = 1
        kernel_noise[2][2] = 1
        noise = cv2.erode(img, kernel_noise, iterations=1)
        cv2.imwrite(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png",
            noise,
        )

        result = Image.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png"
        ).convert("RGBA")
        # result.show()

        if data["size"] == "В размер документа":
            woterm = Image.open(f"./files/br_pass/br_id/watermark.png", "r")
            cropped_result_one = result.crop((432, 596, 1222, 1126))
            width, height = cropped_result_one.size
            new_size = (width + 322, height + 276)
            resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)

            cropped_result_two = result.crop((432, 1146, 1222, 1676))
            width, height = cropped_result_two.size
            new_size = (width + 330, height + 318)
            resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)

            completed_list = Image.new("RGBA", (2481, 3507), (255, 255, 255, 0))
            completed_list.paste(resized_img_1, (118, 1358), resized_img_1)
            completed_list.paste(resized_img_2, (1106, 1344), resized_img_2)
            completed_list = completed_list.crop((122, 1346, 2222, 2165))

            completed_list.save(
                f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
            )
        elif data["size"] == "На фоне":
            cropped_result_one = result.crop((432, 596, 1222, 1126))
            # cropped_result_one.show()
            width, height = cropped_result_one.size
            new_size = (width + 322, height + 276)
            resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)

            cropped_result_two = result.crop((432, 1146, 1222, 1676))
            width, height = cropped_result_two.size
            new_size = (width + 330, height + 318)
            resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)

            completed_list = Image.new("RGBA", (2481, 3507), (255, 255, 255, 0))
            completed_list.paste(resized_img_1, (118, 1358), resized_img_1)
            completed_list.paste(resized_img_2, (1106, 1344), resized_img_2)

            completed_list.save(
                f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
            )
            # path = "./files/uk_pass/background"
            # files = os.listdir(path)
            # kol_files = len(files)
            # number_files = random.randint(1, int(kol_files))
            # x, y = result_go.size
            # result_go.thumbnail(size=(int(x / 3.05), int(y / 3.05)))
            # background = Image.open(f'./files/uk_pass/background/{number_files}.png', 'r')
            # background.paste(result_go, (1518, 818), mask=result_go)
            # background.save(f'./files/uk_pass/photo_usr/{user_id}_completed.png')
            #
            # woterm = Image.open(f'./files/uk_pass/wotermark_background.png', 'r')
            # background.paste(woterm, (0, 0), mask=woterm)
            # x, y = background.size
            # background.thumbnail(size=(int(x / 2), int(y / 2)))
            # background.save(f'./files/uk_pass/photo_usr/{user_id}_completed_wm.png')
        else:
            cropped_result_one = result.crop((432, 596, 1222, 1126))
            # cropped_result_one.show()
            width, height = cropped_result_one.size
            new_size = (width + 322, height + 276)
            resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)

            cropped_result_two = result.crop((432, 1146, 1222, 1676))
            width, height = cropped_result_two.size
            new_size = (width + 330, height + 318)
            resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)

            completed_list = Image.new("RGBA", (2481, 3507), (255, 255, 255, 0))
            completed_list.paste(resized_img_1, (118, 1358), resized_img_1)
            completed_list.paste(resized_img_2, (1106, 1344), resized_img_2)

            completed_list.save(
                f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
            )
        image_path = f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
        path_to_save = f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png"
        paste_watermark(image_path, path_to_save)
        os.remove(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png"
        )

        print("all")

    except Exception as ex:
        print("ошибка process_br_id: ", ex)
        try:
            os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png")
        except:
            pass
        try:
            os.remove(f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png")
        except:
            pass
        return


async def test_save_photo(message: types.Message, state: FSMContext):
    await bot.download_file_by_id(
        file_id=message.document.file_id,
        destination=f"./files/br_pass/br_id/photo_usr/{message.from_user.id}.png",
    )
    await test2(message, state)


async def test2(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["name"] = "john"
        data["family"] = "alegio de visto"
        data["name_father"] = "frolin genr"
        data["name_mother"] = "john gfildt"
        data["date_birth"] = "05.10.1986"
        data["place_birth"] = "Пропустить"
        data["pass_number"] = "Автоматическая генерация"
        data["pass_number_cpf"] = "Автоматическая генерация"
        data["date_doc"] = "12.05.2019"
        data["place_doc"] = "Пропустить"
        data["signature"] = "4"
        data["size"] = "На листе A4"  #'На листе A4' #В размер документа

        img = cv2.imread(
            f"./files/br_pass/br_id/photo_usr/{user_id}.png", cv2.IMREAD_UNCHANGED
        )
        face_cascade = cv2.CascadeClassifier(
            f"./data/haarcascade_frontalface_default.xml"
        )
        faces = face_cascade.detectMultiScale(img, 1.2, 5)
        if len(faces) != 0:
            (x, y, w, h) = faces[0]
            h_top = int(h * 0.4)
            h_bottom = int(h * 0.3)
            w_left = int(w * 0.2)
            w_right = int(w * 0.2)
            x_left = max(0, x - w_left)
            x_right = min(img.shape[1], x + w + w_right)
            w_new = x_right - x_left
            y_top = max(0, y - h_top)
            y_bottom = min(img.shape[0], y + h + h_bottom)
            h_new = y_bottom - y_top

            cropped_img = img[y_top : y_top + h_new, x_left : x_left + w_new]
            resized_img = cv2.resize(
                cropped_img, None, fx=2, fy=2, interpolation=cv2.INTER_AREA
            )
            cv2.imwrite(f"./files/br_pass/br_id/photo_usr/{user_id}.png", resized_img)
            inputt = Image.open(f"./files/br_pass/br_id/photo_usr/{user_id}.png")
            print(inputt.size)

            baseheght = 264
            wpercent = baseheght / float(inputt.size[1])
            wsize = int((float(inputt.size[0]) * float(wpercent)))
            img = inputt.resize((wsize, baseheght))
            output = img
            output = output.rotate(-90, expand=True)
            output.save(f"./files/br_pass/br_id/photo_usr/{user_id}.png")
        else:
            await bot.send_message(user_id, "нету лица на фото")
            return
        print("s photo vse")

        doc = Image.open(f"./files/br_pass/br_id/id.png").convert("RGBA")
        layer_for_photos = Image.new("RGBA", doc.size, (0, 0, 0, 0))
        photo_usr = Image.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}.png"
        ).convert("RGBA")
        layer_for_photos.paste(photo_usr, (845, 759))
        finger_path = f"./files//br_pass/br_id/fingerprints"
        files = os.listdir(finger_path)
        kol_files = len(files)
        number_files_finger = random.randint(1, int(kol_files))
        fingerprint = Image.open(
            f"./files/br_pass/br_id/fingerprints/{number_files_finger}.png"
        ).convert("RGBA")
        layer_for_photos.paste(fingerprint, (554, 798))
        result = Image.alpha_composite(doc, layer_for_photos)

        # ниже подпись
        if data["signature"] != "Не ставить":
            text = f"{pt_transliterate(str(data['family'])).capitalize()}"
            txt_signature = Image.new("RGBA", result.size, (255, 255, 255, 0))
            go_txt_signature = ImageDraw.Draw(txt_signature)
            if data["signature"] == "1":
                fnt1 = ImageFont.truetype(f"./fonts/1.ttf", size=140)
                go_txt_signature.text(
                    xy=(620, 980), text=f"{text}", font=fnt1, fill="#000000"
                )
            elif data["signature"] == "2":
                fnt2 = ImageFont.truetype(f"./fonts/2.ttf", size=70)
                go_txt_signature.text(
                    xy=(620, 985),
                    text=f"{text}",
                    font=fnt2,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "3":
                fnt3 = ImageFont.truetype(f"./fonts/3.ttf", size=100)
                go_txt_signature.text(
                    xy=(620, 985),
                    text=f"{text}",
                    font=fnt3,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "4":
                fnt4 = ImageFont.truetype(f"./fonts/4.ttf", size=40)
                go_txt_signature.text(
                    xy=(620, 1000),
                    text=f"{text}",
                    font=fnt4,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "5":
                fnt5 = ImageFont.truetype(f"./fonts/5.ttf", size=90)
                go_txt_signature.text(
                    xy=(620, 1000),
                    text=f"{text}",
                    font=fnt5,
                    fill="#000000",
                    stroke_width=1,
                )
            elif data["signature"] == "6":
                fnt6 = ImageFont.truetype(f"./fonts/6.ttf", size=40)
                go_txt_signature.text(
                    xy=(620, 1000), text=f"{text}", font=fnt6, fill="#000000"
                )
            txt_blur = txt_signature.filter(ImageFilter.GaussianBlur(radius=1))

            # txt_blur = txt_signature
            result = Image.alpha_composite(result, txt_blur)

        txt = Image.new("RGBA", result.size, (255, 255, 255, 0))
        fnt_ocrb = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=18
        )
        fnt_ocrb_one = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=20
        )
        fnt_ocrb_two = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=17
        )
        fnt_ocrb_two_cpf = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=16
        )
        fnt_ocrb_three = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=19
        )
        fnt_meyro = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/meiryo.ttc", size=16
        )
        fnt_arial = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/ariblk.ttf", size=14
        )
        fnt_ocr_bold = ImageFont.truetype(
            f"./files/br_pass/br_id/fonts/OCR B Pro.TTF", size=26
        )
        go_txt = ImageDraw.Draw(txt)

        # go_txt.text(xy=(800, 740), text=f"0000",
        #                    font=fnt_arial,
        #                    fill=(55, 58, 55, 255))

        # random_4_c = random.randint(1000, 9999)
        # layer_4_c = Image.new('RGBA', (50, 50), (255, 255, 255, 0))
        # text_image_4_c = ImageDraw.Draw(layer_4_c)

        # Создать пустое изображение для текста
        # random_4_c = '0000'
        random_4_c = f"0{str(random.randint(100, 999))}"
        mrz_layer = Image.new("RGBA", result.size, (255, 255, 255, 0))
        text_width, text_height = go_txt.textsize(str(random_4_c), fnt_arial)
        text_image_mrz = Image.new(
            "RGBA", (text_width + 100, text_height + 100), (255, 255, 255, 0)
        )
        text_draw_mrz = ImageDraw.Draw(text_image_mrz)
        text_draw_mrz.text(
            xy=(0, 0), text=f"{random_4_c}", font=fnt_arial, fill=(55, 58, 55, 255)
        )

        new_height_mrz = int(text_image_mrz.height) + 20
        rr_mrz = text_image_mrz.resize((text_image_mrz.width, new_height_mrz))
        rr_mrz = rr_mrz.rotate(-90, expand=True, resample=Image.BICUBIC)

        mrz_layer.paste(rr_mrz, (696, 852))
        # mrz_layer.paste(text_image_mrz, (100, 2247))
        result = Image.alpha_composite(result, mrz_layer)
        go_txt.text(
            xy=(1072, 1572),
            text=random_4_c,
            font=fnt_ocrb_two_cpf,
            fill=(44, 42, 29, 255),
        )

        shag = 1
        text_place_b = f"{data['name'].upper()} {data['family'].upper()}"
        go_txt.text(
            xy=(532, 1287), text=text_place_b, font=fnt_ocr_bold, fill=(44, 42, 29, 255)
        )
        # w = fnt_ocr_bold.getsize(f"{text_place_b[0]}")[0]
        # for bbrva in text_place_b:
        #     go_txt.text(xy=((450 + w * shag) * 1.05, 1295), text=bbrva, font=fnt_ocr_bold,
        #                 fill=(44, 42, 29, 255))
        #     shag += 1
        # # go_txt.text(xy=(541, 1295), text=f"{str(data['name']).upper()}", font=fnt_ocrb,
        # #             fill=(44, 42, 29, 255))

        shag = 1
        text_place_b = f"{data['name_father'].upper()}"
        w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
        for bbrva in text_place_b:
            go_txt.text(
                xy=((450 + w * shag) * 1.17, 1355),
                text=bbrva,
                font=fnt_ocrb,
                fill=(44, 42, 29, 255),
            )
            shag += 1
        # go_txt.text(xy=(541, 1355), text=f"{str(data['name_father']).upper()}", font=fnt_ocrb,
        #             fill=(44, 42, 29, 255))

        shag = 1
        text_place_b = f"{data['name_mother'].upper()}"
        w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
        for bbrva in text_place_b:
            go_txt.text(
                xy=((450 + w * shag) * 1.17, 1393),
                text=bbrva,
                font=fnt_ocrb,
                fill=(44, 42, 29, 255),
            )
            shag += 1
        # go_txt.text(xy=(540, 1393), text=f"{str(data['name_mother']).upper()}", font=fnt_ocrb,
        #             fill=(44, 42, 29, 255))

        # #############################
        shag = 1
        if data["place_birth"] == "Пропустить":
            text_place_b = f"RIO DE JANEIRO/RJ".upper()
            w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((450 + w * shag) * 1.17, 1451),
                    text=bbrva,
                    font=fnt_ocrb_three,
                    fill=(44, 42, 29, 255),
                )
                shag += 1
        else:
            text_place_b = f"{data['place_birth']}".upper()
            w = fnt_ocrb.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((450 + w * shag) * 1.17, 1451),
                    text=bbrva,
                    font=fnt_ocrb_three,
                    fill=(44, 42, 29, 255),
                )
                shag += 1

        shag = 1
        if data["place_doc"] == "Пропустить":
            text_pic = Image.open(f"./files/br_pass/br_id/doc_origem.png").convert(
                "RGBA"
            )
            result = Image.alpha_composite(result, text_pic)
        else:
            text_place_b = f"{data['place_doc']}".upper()
            w = fnt_meyro.getsize(f"{text_place_b[0]}")[0]
            for bbrva in text_place_b:
                go_txt.text(
                    xy=((460 + w * shag) * 1.14, 1493),
                    text=bbrva,
                    font=fnt_meyro,
                    fill=(44, 42, 29, 255),
                )
                shag += 1

        # shag = 1
        # text_place_b = f"rio  de  janeiro".upper()
        # w = fnt_meyro.getsize(f"{text_place_b[0]}")[0]
        # for bbrva in text_place_b:
        #     go_txt.text(xy=((450 + w * shag) * 1.12, 1513), text=bbrva, font=fnt_meyro,
        #                 fill=(44, 42, 29, 255))
        #     shag += 1
        # # go_txt.text(xy=(536, 1513), text=f"rio  de  janeiro".upper(), font=fnt_meyro,
        # #                 fill=(44, 42, 29, 255))
        #############################

        if data["pass_number"] == "Автоматическая генерация":
            label = f"09.{random.randint(100, 999)}.{random.randint(100, 999)}-{random.randint(0, 9)}"
        else:
            label = f"{data['pass_number']}"
        go_txt.text(
            xy=(617, 1233), text=f"{label}", font=fnt_ocr_bold, fill=(44, 42, 29, 255)
        )
        if data["pass_number_cpf"] == "Автоматическая генерация":
            label_cpf = f"070.{random.randint(100, 999)}.{random.randint(100, 999)}-{random.randint(10, 99)}"
        else:
            label_cpf = f"{data['pass_number_cpf']}"
        shag = 1
        text_place_b = f"{label_cpf}".upper()
        w = fnt_ocrb_two.getsize(f"{text_place_b[0]}")[0]
        for bbrva in text_place_b:
            go_txt.text(
                xy=((430 + w * shag) * 1.23, 1547),
                text=bbrva,
                font=fnt_ocrb_two_cpf,
                fill=(44, 42, 29, 255),
            )
            shag += 1
        # go_txt.text(xy=(541, 1547), text=f"{label_cpf}",
        #             font=fnt_ocrb_two,
        #             fill=(44, 42, 29, 255))

        date_doc = data["date_doc"]
        go_txt.text(
            xy=(984, 1235),
            text=f"{date_doc[:2]}/{date_doc[3:5]}/{date_doc[6:10]}",
            font=fnt_ocrb_one,
            fill=(44, 42, 29, 255),
        )
        birth = data["date_birth"]
        go_txt.text(
            xy=(948, 1450),
            text=f"{birth[:2]}/{birth[3:5]}/{birth[6:10]}",
            font=fnt_ocrb_one,
            fill=(44, 42, 29, 255),
        )
        result = Image.alpha_composite(result, txt)

        result.save(
            f"/files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png"
        )
        # Добавляем зернистость
        img = cv2.imread(
            f"/files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png",
            cv2.IMREAD_UNCHANGED,
        )
        kernel_noise = np.zeros((3, 3), np.uint8)
        kernel_noise[1][1] = 1
        kernel_noise[1][2] = 1
        kernel_noise[2][2] = 1
        noise = cv2.erode(img, kernel_noise, iterations=1)
        cv2.imwrite(
            f"/files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png",
            noise,
        )

        result = Image.open(
            f"/files/br_pass/br_id/photo_usr/{user_id}_completed123123123123123123.png"
        ).convert("RGBA")
        # result.show()

        if data["size"] == "В размер документа":
            woterm = Image.open(f"/files/br_pass/br_id/watermark.png", "r")
            cropped_result_one = result.crop((432, 596, 1222, 1126))
            # cropped_result_one.show()
            width, height = cropped_result_one.size
            new_size = (width + 322, height + 276)
            resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)
            # resized_img_1.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_1.png')

            cropped_result_two = result.crop((432, 1146, 1222, 1676))
            width, height = cropped_result_two.size
            new_size = (width + 330, height + 318)
            resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)
            # resized_img_2.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_2.png')

            completed_list = Image.new("RGBA", (2481, 3507), (255, 255, 255, 0))
            completed_list.paste(resized_img_1, (118, 1358), resized_img_1)
            completed_list.paste(resized_img_2, (1106, 1344), resized_img_2)
            completed_list = completed_list.crop((122, 1346, 2222, 2165))

            completed_list.save(
                f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
            )

            # cropped_result_one = result.crop((432, 596, 1222, 1126))
            # # cropped_result_one.show()
            # width, height = cropped_result_one.size
            # new_size = (width + 296, height + 276)
            # resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)
            # # resized_img_1.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_1.png')
            #
            # cropped_result_two = result.crop((432, 1146, 1222, 1676))
            # width, height = cropped_result_two.size
            # new_size = (width + 356, height + 318)
            # resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)
            # # resized_img_2.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_2.png')
            #
            # completed_list = Image.new("RGBA", (2100, 820), (255, 255, 255, 0))
            # completed_list.paste(resized_img_1, (45, 52), resized_img_1)
            # completed_list.paste(resized_img_2, (1025, 52), resized_img_2)
            # completed_list.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed.png')
            # white = Image.new("RGB", size=(2100, 820), color='White')
            # white.paste(resized_img_1, (45, 52), resized_img_1)
            # white.paste(resized_img_2, (1025, 52), resized_img_2)
            # white.paste(woterm, (0, 0), mask=woterm)
            # white.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png')
            # #№№№№

            # cropped_result_one = result.crop((432, 596, 1222, 1126))
            # cropped_result_one.show()
            # width, height = cropped_result_one.size
            # new_size = (width + 316, height + 170)
            # resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BOX)
            # resized_img_1.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_1.png')
            #
            # white_one = Image.new("RGB", size=resized_img_1.size, color='White')
            # white_one.paste(resized_img_1, (0, 0), mask=resized_img_1)
            # white_one.paste(woterm, (0, 0), mask=woterm)
            # white_one.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_wm_1.png')
            #
            # cropped_result_two = result.crop((432, 1146, 1222, 1676))
            # width, height = cropped_result_two.size
            # new_size = (width + 329, height + 203)
            # resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BOX)
            # resized_img_2.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_2.png')
            # white_two = Image.new("RGB", size=resized_img_2.size, color='White')
            # white_two.paste(cropped_result_two, (0, 0), mask=cropped_result_two)
            # white_two.paste(woterm, (0, 0), mask=woterm)
            # white_two.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_wm_2.png')
        elif data["size"] == "На фоне":
            cropped_result_one = result.crop((432, 596, 1222, 1126))
            # cropped_result_one.show()
            width, height = cropped_result_one.size
            new_size = (width + 322, height + 276)
            resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)
            # resized_img_1.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_1.png')

            cropped_result_two = result.crop((432, 1146, 1222, 1676))
            width, height = cropped_result_two.size
            new_size = (width + 330, height + 318)
            resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)
            # resized_img_2.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_2.png')

            completed_list = Image.new("RGBA", (2481, 3507), (255, 255, 255, 0))
            completed_list.paste(resized_img_1, (118, 1358), resized_img_1)
            completed_list.paste(resized_img_2, (1106, 1344), resized_img_2)

            completed_list.save(
                f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
            )

            # path = f"./files//uk_pass/background"
            # files = os.listdir(path)
            # kol_files = len(files)
            # number_files = random.randint(1, int(kol_files))
            # x, y = result_go.size
            # result_go.thumbnail(size=(int(x / 3.05), int(y / 3.05)))
            # background = Image.open(f'./files/uk_pass/background/{number_files}.png', 'r')
            # background.paste(result_go, (1518, 818), mask=result_go)
            # background.save(f'./files/uk_pass/photo_usr/{user_id}_completed.png')
            #
            # woterm = Image.open(f'./files/uk_pass/wotermark_background.png', 'r')
            # background.paste(woterm, (0, 0), mask=woterm)
            # x, y = background.size
            # background.thumbnail(size=(int(x / 2), int(y / 2)))
            # background.save(f'./files/uk_pass/photo_usr/{user_id}_completed_wm.png')
        else:
            cropped_result_one = result.crop((432, 596, 1222, 1126))
            # cropped_result_one.show()
            width, height = cropped_result_one.size
            new_size = (width + 322, height + 276)
            resized_img_1 = cropped_result_one.resize(new_size, resample=Image.BICUBIC)
            # resized_img_1.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_1.png')

            cropped_result_two = result.crop((432, 1146, 1222, 1676))
            width, height = cropped_result_two.size
            new_size = (width + 330, height + 318)
            resized_img_2 = cropped_result_two.resize(new_size, resample=Image.BICUBIC)
            # resized_img_2.save(f'./files/br_pass/br_id/photo_usr/{user_id}_completed_2.png')

            completed_list = Image.new("RGBA", (2481, 3507), (255, 255, 255, 0))
            completed_list.paste(resized_img_1, (118, 1358), resized_img_1)
            completed_list.paste(resized_img_2, (1106, 1344), resized_img_2)

            completed_list.save(
                f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png"
            )

        paste_watermark(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed.png",
            f"./files/br_pass/br_id/photo_usr/{user_id}_wm.png",
        )

        print("all")


async def test_vidacha(message: types.Message):
    user_id = message.from_user.id
    filename = f"{user_id}_completed_wm.png"
    folderpath = f"./files//br_pass/br_id/photo_usr"
    file_exist = await check_file_exist_br_id(filename, folderpath)
    print(file_exist)
    if file_exist:
        async with aiofiles.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png", "rb"
        ) as f:
            await bot.send_document(chat_id=user_id, document=f)
        await bot.send_message(
            user_id, "Завершите покупку документа.", reply_markup=client_kb.kb_br_finish
        )
    else:
        async with aiofiles.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm_1.png", "rb"
        ) as f:
            await bot.send_document(chat_id=user_id, document=f)
        async with aiofiles.open(
            f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm_2.png", "rb"
        ) as f:
            await bot.send_document(chat_id=user_id, document=f)
        await bot.send_message(
            user_id, "Завершите покупку документа.", reply_markup=client_kb.kb_br_finish
        )


async def check_file_exist_br_id(filename: str, folderpath: str) -> bool:
    filepath = folderpath + "/" + filename
    print(filepath)
    return await aiofiles.os.path.exists(filepath)


async def handler_generating_id(user_id, state):
    async with state.proxy() as data:
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Имя: {data["name"]}\n'
            f'✅ Имя отца: {data["name_father"]}\n'
            f'✅ Имя матери: {data["name_mother"]}\n'
            f'✅ Дата рождения: {data["date_birth"]}\n'
            f'✅ Место рождения: {data["place_birth"]}\n'
            f'✅ Номер паспорта (RG): {data["pass_number"]}\n'
            f'✅ Номер паспорта (CPF): {data["pass_number_cpf"]}\n'
            f'✅ Дата выдачи: {data["date_doc"]}\n'
            f'✅ Место выдачи: {data["place_doc"]}\n'
            f"✅ Фотография:\n"
            f'✅ Подпись: {data["signature"]}\n'
            f'✅ Размер документа: {data["size"]}',
        )
        msg_delete = await bot.send_message(
            user_id,
            "Ожидайте генерируется...",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
            try:
                thr = threading.Thread(
                    target=process_generate_id,
                    args=(user_id, data),
                    name=f"thr-{user_id}",
                )
                thr.start()
                while thr.is_alive():
                    await asyncio.sleep(1)
                async with aiofiles.open(
                    f"./files/br_pass/br_id/photo_usr/{user_id}_completed_wm.png", "rb"
                ) as f:
                    await bot.send_document(chat_id=user_id, document=f)
                await bot.send_message(
                    user_id,
                    "Завершите покупку документа.",
                    reply_markup=client_kb.kb_br_finish_id,
                )
                try:
                    await messagetoedit.delete()
                    await bot.delete_message(
                        chat_id=user_id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                await FSM.change_br_id.set()
            except Exception as ex:
                print("Ошибка в генерации br id:", ex)
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "Ошибка при генерации, проверьте введенные данные",
                        reply_markup=client_kb.kb_br_change_error,
                    )
                    data["message_edit"] = messagetoedit["message_id"]
                    data["msg_delete"] = msg_delete["message_id"]
                    await FSM.change_br_id.set()


def process_change_signature(user_id, data):
    text = "Name"
    txt = Image.new("RGBA", (1800, 600), (255, 255, 255, 0))
    go_txt = ImageDraw.Draw(txt)
    fnt1 = ImageFont.truetype(f"./fonts/1.ttf", size=270)
    go_txt.text(xy=(200, 50), text=f"{text}", font=fnt1, fill="#000000")
    fnt2 = ImageFont.truetype(f"./fonts/2.ttf", size=190)
    go_txt.text(xy=(800, 50), text=f"{text}", font=fnt2, fill="#000000", stroke_width=1)
    fnt3 = ImageFont.truetype(f"./fonts/3.ttf", size=200)
    go_txt.text(
        xy=(1400, 50), text=f"{text}", font=fnt3, fill="#000000", stroke_width=1
    )
    fnt4 = ImageFont.truetype(f"./fonts/4.ttf", size=100)
    go_txt.text(
        xy=(200, 400), text=f"{text}", font=fnt4, fill="#000000", stroke_width=1
    )
    fnt5 = ImageFont.truetype(f"./fonts/5.ttf", size=150)
    go_txt.text(
        xy=(800, 400), text=f"{text}", font=fnt5, fill="#000000", stroke_width=1
    )
    fnt6 = ImageFont.truetype(f"./fonts/6.ttf", size=80)
    go_txt.text(xy=(1400, 400), text=f"{text}", font=fnt6, fill="#000000")
    fnt66 = ImageFont.truetype(f"./fonts/66.ttf", size=80)
    go_txt.text(xy=(1430, 440), text=f"k", font=fnt66, fill="#000000")
    txt_blur = txt.filter(ImageFilter.GaussianBlur(radius=1))
    holst = Image.new("RGBA", (1800, 600), (255, 255, 255, 255))
    choose_signature = Image.alpha_composite(holst, txt_blur)
    choose_signature.save(
        f"./files/br_pass/br_id/photo_usr/{user_id}_choose_signature.png"
    )
